package look4ss.aplicativo;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.annotation.NonNull;
import android.support.design.widget.TextInputLayout;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.sdsmdg.tastytoast.TastyToast;

public class ActivityLogin extends AppCompatActivity {
    private Button botaoLogin;
    private TextView botaoRegistrar, esqueceuSenha;
    private EditText enderecoEmail;
    private EditText usuarioSenha;
    private TextInputLayout txtEmail;
    private TextInputLayout txtSenha;
    private ProgressBar barraDeLoading;
    private CheckBox lembrar;
    private FirebaseAuth firebaseAuth;
    private SharedPreferences loginLembrar;
    private SharedPreferences.Editor loginLembrar_edt;
    private boolean salvarLogin;
    public static String ir = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        botaoLogin = findViewById(R.id.login);
        botaoRegistrar = findViewById(R.id.criarconta_botao);
        esqueceuSenha = findViewById(R.id.esqueceusenha);
        enderecoEmail = findViewById(R.id.endereco_de_email);
        usuarioSenha = findViewById(R.id.senha_login);
        txtEmail = findViewById(R.id.layout_entrada_texto);
        txtSenha = findViewById(R.id.layout_entrada_texto2);
        barraDeLoading = findViewById(R.id.barraLoading);
        lembrar = findViewById(R.id.lembrar_login);
        firebaseAuth = FirebaseAuth.getInstance();
        loginLembrar = getSharedPreferences("loginPrefs", MODE_PRIVATE);
        loginLembrar_edt = loginLembrar.edit();

        txtEmail.setHintEnabled(true);
        txtSenha.setHintEnabled(true);

        botaoLogin.setTextColor(ContextCompat.getColor(ActivityLogin.this, R.color.textoBotoes));

        botaoRegistrar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(ActivityLogin.this, ActivityRegistro.class));
            }
        });

        esqueceuSenha.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(ActivityLogin.this, ActivityRecuperarSenha.class));
            }
        });

        salvarLogin = loginLembrar.getBoolean("salvarLogin", true);
        if (salvarLogin == true) {
            enderecoEmail.setText(loginLembrar.getString("email", ""));
            usuarioSenha.setText(loginLembrar.getString("senha", ""));
            lembrar.setChecked(true);
            }
        botaoLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                InputMethodManager inmng = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
                inmng.hideSoftInputFromWindow(enderecoEmail.getWindowToken(), 0);

                final String email = enderecoEmail.getText().toString();
                String senha = usuarioSenha.getText().toString();

                if (lembrar.isChecked()) {
                    loginLembrar_edt.putBoolean("salvarLogin", true);
                    loginLembrar_edt.putString("email", email);
                    loginLembrar_edt.putString("senha", senha);
                    loginLembrar_edt.commit();
                } else {
                    loginLembrar_edt.clear();
                    loginLembrar_edt.commit();
                }

                if(TextUtils.isEmpty(email)) {
                    txtEmail.setError(getString(R.string.erro_email_vazio));
                    return;
                } else {
                    txtEmail.setError(null);
                } if(TextUtils.isEmpty(senha)) {
                    txtSenha.setError(getString(R.string.erro_senha_vazia));
                } else {
                    txtSenha.setError(null);
                }

                barraDeLoading.setVisibility(View.VISIBLE);

                firebaseAuth.signInWithEmailAndPassword(email, senha).addOnCompleteListener(ActivityLogin.this, new OnCompleteListener<AuthResult>() {
                    @Override
                    public void onComplete(@NonNull Task<AuthResult> task) {
                        barraDeLoading.setVisibility(View.GONE);
                       if(!task.isSuccessful()){
                           TastyToast.makeText(getApplicationContext(), getString(R.string.credenciais_erradas), Toast.LENGTH_LONG, TastyToast.ERROR);
                       }else{
                           if(ir.equals("enviar"))
                               startActivity(new Intent(ActivityLogin.this, ActivityEnviar.class));
                               finish();
                        }if(ir.equals("config")){
                            startActivity(new Intent(ActivityLogin.this, ActivityEditarPerfil.class));
                            finish();
                        }
                    }
                });
            }
        });
    }
}